#include "./UDPIO.h"

using namespace Network;
using namespace std;

UDPIO::UDPIO() { }
UDPIO::~UDPIO() { }

void UDPIO::wait(float seconds) {
#ifdef _WIN32
		Sleep((int)(seconds * 1000.0f));
#else
		usleep((int)(seconds * 1000000.0f));
#endif
}

Packet UDPIO::receivePacket() {
	char msg[BUF_SIZE+3];
	sockaddr_in from;
	socklen_t fromLength = sizeof(from);
	int bytes_read = recvfrom(sock_, (char*)msg, BUF_SIZE + 3, 0, (sockaddr*)&from, &fromLength);

	std::cout << "Receiving: " << msg << std::endl;

//	if ( bytes_read <= 3 )
//		return NULL;
//	timeoutAccumulator_ = 0.0f;
	Packet packet;
	packet.type_ = msg[0];
	packet.msgNo_ = msg[1];
	packet.uid_ = msg[2];
	packet.from_ = inet_ntoa(from.sin_addr);
	packet.length_ = bytes_read;
	packet.msg_ = msg[3];
//	memcpy(data, &msg[3], size - 3);
	return packet;
}

int UDPIO::sendPacket(Packet packet) {
	char msg[BUF_SIZE+3];
	msg[0] = packet.type_;
	msg[1] = packet.msgNo_;
	msg[2] = packet.uid_;
	strcpy(&msg[3], packet.msg_.c_str());
	// XXX: Michale - moze strlen(mesg) zamiast sizeof mesg? To drugie chyba zwroci rozmiar tablicy
	// YYY: to chyba nie ma znaczenia, bo i tak odbieramy potem pakiety o stalej dlugosci.
	// liczba 32 byla oczywiscie arbitralna
	// - dzielenie pakietow (?)
	std::cout << "Sending: " << msg << std::endl;
	return sendto(sock_, msg, sizeof msg ,0,(struct sockaddr *) &target_,sizeof target_);
}

